package com.alogic.validator.impl;

import com.alogic.validator.Validator;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;


/**
 * 相似性判断
 *
 * @since 1.6.13.28 [20201218 duanyy] <br>
 */
public abstract class Similar extends Validator.Abstract{
    protected String $key;

    @Override
    public void configure(Properties p) {
        super.configure(p);
        $key = PropertiesConstants.getRaw(p,"key",$key);
    }

    @Override
    public boolean check(String value, Properties ctx,boolean throwException) {
        boolean result = true;
        String[] keys = PropertiesConstants.transform(ctx,$key,"").split(",");
        for (String key:keys){
            if (StringUtils.isNotEmpty(key)){
                result = !isSimilar(key,value);
                if (!result){
                    break;
                }
            }
        }

        if (!result && throwException){
            throw new BaseException(getCode(ctx),getMessage(ctx));
        }

        return result;
    }

    protected abstract boolean isSimilar(String key, String value);

    @Override
    public boolean check(String value, Properties ctx, Listener listener) {
        boolean result = check(value,ctx,listener);
        if (listener != null){
            listener.result(result,value,this,ctx);
        }

        return result;
    }
}